package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import com.zzyl.common.utils.thread.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取header中的token
        String authorization = request.getHeader("authorization");
        // 如果token为空,响应401,重新登录
        if (authorization == null) {
//            response.setStatus(401);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 解析token
        Claims claims = tokenService.parseToken(authorization);
        // 如果解析失败,响应401,重新登录
        if (claims == null) {
            // 响应401,重新登录
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 解析token中的数据,拿到userid
//        Long userId = (Long) claims.get("userId");
        Long userId = MapUtil.get(claims, "userId", Long.class);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 将用户id放入ThreadLocal中
        UserThreadLocal.set(userId);
        // 方行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        //        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
